import WebGl from '@/modules/three';
// import fontJson from 'three/examples/fonts/helvetiker_regular.typeface.json'
const fontJson = require('three/examples/fonts/helvetiker_regular.typeface.json');

const {
  Three,
  TWEEN,
  OrbitControls,
  dat,
  Stats,
  OBJLoader,
  MTLLoader,
  GLTFLoader,
} = WebGl;

class WebGlControl {
  private container: any;
  private camera: any;
  private scene: any;
  private renderer: any;
  private stats: any;
  private animateFrame: any;
  private tween: any;
  private controls: any;
  private clock: any = new Three.Clock();
  private mixer: any; //glb的animation

  private Geometrys: {
    starsGeometry?: any;
  } = {}; //保存所有Geometry，方便统一销毁
  private Materials: {
    starsMaterial?: any;
  } = {}; //保存所有Material，方便统一销毁
  private particleSystem: any;

  private GuiInit: any = null;
  private guiData: any = {
    x: 0.005,
    color: '#000000',
    autoRotate: true,
  };
  private birdAnimation: {
    direction: any; // 方向
    directionTrend: any; // 方向变换的方向
    speed: number; //速度
    speedDecay: number; //速度衰减，-1,1
  } = {
    direction: new Three.Vector3(0, 1, 0),
    directionTrend: new Three.Vector3(0, 1, 0),
    speed: 15,
    speedDecay: 0,
  };

  public init = (id: string) => {
    // if(this.scene) {return}
    this.container = document.getElementById(id);
    let width = this.container.clientWidth,
      height = this.container.clientHeight;

    this.scene = new Three.Scene();

    this.camera = new Three.PerspectiveCamera(45, width / height, 1, 500);
    this.camera.position.x = 0;
    this.camera.position.y = 0;
    this.camera.position.z = 80;
    this.camera.lookAt(this.scene.position);

    this.renderer = new Three.WebGLRenderer();
    // this.renderer.setClearColor( 0xffffff );
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(width, height);
    this.container.appendChild(this.renderer.domElement);

    this.controls = new OrbitControls(this.camera, this.renderer.domElement);
    this.controls.enableDamping = true; //阻尼
    this.controls.dampingFactor = 0.1; //阻尼

    this.addThings();
    this.addLight(); //+光源
    this.animate(); //开始动
    this.initStats();

    this.initGui();
  };
  public destroy = () => {
    this.toggleGui(0);
    Object.values(this.Geometrys).forEach((e) => {
      e.dispose();
    });
    Object.values(this.Materials).forEach((e) => {
      e.dispose();
    });
    this.scene.clear();
    this.renderer.dispose();
    this.renderer.forceContextLoss();
    this.camera = null;
    this.scene = null;
    this.renderer = null;
    this.GuiInit = null;
    this.stats = null;
    if (this.tween) {
      this.tween.stop();
      this.tween = null;
    }
    cancelAnimationFrame(this.animateFrame);
  };

  private initStats = () => {
    this.stats = new Stats();
    this.stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    this.stats.dom.style.position = 'absolute';
    this.container.appendChild(this.stats.dom);
  };

  public initGui = () => {
    if (this.GuiInit) {
      this.toggleGui();
      return;
    }
    this.GuiInit = new dat.GUI({
      // autoPlace: false
    });

    this.GuiInit.domElement.style.position = 'absolute';
    this.GuiInit.domElement.style.right = '10px';
    this.GuiInit.domElement.style.top = '10px';

    let GuiController = this.GuiInit.addFolder('控制窗口');
    GuiController.add(this.guiData, 'x', -0.1, 0.1, 0.005).name('自转速度');
    GuiController.addColor(this.guiData, 'color').name('背景颜色');
    GuiController.open();

    // let cubeGui = this.GuiInit.addFolder("cube position");
    // cubeGui.open()
  };

  public toggleGui = (state: any = null) => {
    if (!this.GuiInit || !this.GuiInit.domElement) {
      return;
    }
    let display = this.GuiInit.domElement.style.display == 'none' ? '' : 'none';
    if (state == 0) {
      display = 'none';
    }
    this.GuiInit.domElement.style.display = display;
  };

  private addLight = () => {
    let ambi = new Three.AmbientLight(0x686868);
    this.scene.add(ambi);
    let dirLight = new Three.DirectionalLight(0xffffff);
    dirLight.position.set(550, 100, 550);
    dirLight.intensity = 0.6;
    this.scene.add(dirLight);
    // let light = new Three.PointLight( 0xFFFF00 );
    // light.position.set( -100, 100, 0 );
    // this.scene.add(light);
  };

  private addThings = () => {
    // const axesHelper = new Three.AxesHelper( 800 );
    // this.scene.add( axesHelper )  //添加坐标轴；红线是X轴，绿线是Y轴，蓝线是Z轴

    this.addStars();
    this.addGlb();

    this.initTween();
  };

  private addStars = () => {
    let mtlLoader = new MTLLoader();
    mtlLoader.load('../models/stars.mtl', (materials) => {
      materials.preload();
      let objLoader = new OBJLoader();
      objLoader.setMaterials(materials);
      objLoader.load(
        '../models/stars.obj',
        (object) => {
          object.traverse((child) => {
            if (child instanceof Three.Mesh) {
              child.material.shininess = 0.001;
              child.material.reflectivity = 0.1;
              object.receiveShadow = true;
              object.castShadow = true;
            }
          });
          console.log('stars', object);
          object.position.set(0, 0, -20);
          object.scale.set(4, 4, 4);
          object.receiveShadow = true;
          object.castShadow = true;
          this.scene.add(object);
        },
        (xhr) => {
          console.log((xhr.loaded / xhr.total) * 100 + '% loaded');
        },
        (error) => {
          console.log(error);
        },
      );
    });
  };
  private addGlb = () => {
    const gltfs = ['../models/Parrot.glb', '../models/Flamingo.glb'];
    const colors = [0xccffff, 0xffdeff];
    const sizes = [0.2, 0.1];
    const selectModel = Math.floor(Math.random() * gltfs.length);
    new GLTFLoader().load(gltfs[selectModel], (gltf) => {
      console.log('glbbbbb:', gltf, gltf.animations);
      // gltf.animations;
      this.mixer = new Three.AnimationMixer(gltf.scene);
      gltf.animations.forEach((animations) => {
        this.mixer.clipAction(animations).play();
      });

      const bird = gltf.scene.children[0];
      const birdGeo = bird.geometry;
      bird.scale.set(0.3, 0.3, 0.3);
      this.scene.add(gltf.scene);
    });
  };

  private initTween = () => {
    // var pos: any = { val: 1 };
    // this.tween = new TWEEN.Tween(pos)
    //   .to({ val: 0 }, 1000)
    //   .easing(TWEEN.Easing.Quadratic.InOut)
    //   .delay(200)
    //   .onUpdate(callback);
    // let tweenBack = new TWEEN.Tween(pos)
    //   .to({ val: 1 }, 1000)
    //   .easing(TWEEN.Easing.Quadratic.InOut)
    //   .delay(200)
    //   .onUpdate(callback);
    // this.tween.chain(tweenBack);
    // tweenBack.chain(this.tween);
    // this.tween.start();
    // let that = this;
    // function callback(res) {
    //   that.Materials.starsMaterial.uniforms.val.value = res.val;
    // }
  };

  private animate = () => {
    // if(!this.renderer){return;}
    if (this.stats) {
      this.stats.begin();
    }

    this.render();
    TWEEN.update();
    this.controls.update();

    if (this.stats) {
      this.stats.end();
    }
    this.animateFrame = requestAnimationFrame(this.animate);
  };
  private render = () => {
    const delta = this.clock.getDelta();
    if (this.mixer) this.mixer.update(delta);

    if (!this.renderer) {
      return;
    }
    this.renderer.setClearColor(this.guiData.color, 1.0);
    // if(this.guiData.autoRotate){
    // }
    this.renderer.render(this.scene, this.camera);
  };
}

const webGlControl = new WebGlControl();
export default webGlControl;
